package org.utils.xml.xmlupdater;

import java.util.ArrayList;

import org.utils.common.InitException;
import org.utils.xml.XMLDataNode;

public class RulesHandler
{
  private static RulesHandler instance = null;

  public static void init(XMLDataNode config) throws InitException
  {
    instance = new RulesHandler(config);
  }

  public static RulesHandler getInstance() throws InitException
  {
    if (instance == null)
      throw new InitException("This handler must have been initialized before you can use it");
    return instance;
  }

  private ArrayList rules = new ArrayList();

  public RulesHandler(XMLDataNode config) throws InitException
  {
    if (config == null)
      throw new InitException("Missing tag <Rules> in the rules document");
    ArrayList childs = config.getChildren();
    for (int i = 0; i < childs.size(); i++)
    {
      XMLDataNode child = (XMLDataNode) childs.get(i);
      String name = child.getName().toLowerCase();
      if (name.equals("update"))
	 rules.add( new UpdateRule(child) );
    }
  }

  public String toString()
  {
    StringBuffer buffer = new StringBuffer();
    buffer.append("Rules:");
    buffer.append( System.getProperty("line.separator") );
    for (int i = 0; i < rules.size(); i++)
    {
      buffer.append(rules.get(i).toString());
      buffer.append( System.getProperty("line.separator") );
    }
    return buffer.toString();
  }

  public XMLDataNode applyRules(XMLDataNode root)
  {
    for (int i = 0; i < rules.size(); i++)
      root = ((AbstractRule) rules.get(i)).apply(root);
    return root;
  }
}
